//
//  YPHomePageFragmentVC.m
//  WHISPER
//
//  Created by lanou3g on 15/12/17.
//  Copyright © 2015年 王艳苹. All rights reserved.
//

#import "YPHomePageFragmentVC.h"
#import "YPFragmentCell.h"
#import "YPNetWorking.h"
#import "YPMakeURL.h"
#import "leftimageButton.h"
#import "YPFramentModel.h"
#import "UIImageView+WebCache.h"
#import "UIView+Extention.h"
#import "MJRefresh.h"
#import "YPUser.h"
#import "YPWebViewVC.h"
#import "YPLikeHelper.h"
#import "YPDataBase.h"
#import "YPJudgeNet.h"

static YPHomePageFragmentVC *fragmentVC = nil;
@interface YPHomePageFragmentVC ()

@property (nonatomic,strong) NSMutableArray *framentList;
@property (nonatomic,assign) float  imageHight;
@property (nonatomic,assign) float worldH;
@property (nonatomic,strong) YPLikeHelper *like;
@property (nonatomic,strong) YPDataBase *database;

@end

@implementation YPHomePageFragmentVC
static NSInteger flag = 0;
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.backgroundColor = [UIColor whiteColor];
      [self.tableView registerNib:[UINib nibWithNibName:@"YPFragmentCell" bundle:nil] forCellReuseIdentifier:@"YPFragmentCell"];

    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(upFreash)] ;
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(downFresh)];
    [self JudgeNet];
}
- (void)JudgeNet{
    if ([[YPJudgeNet shareJudgeNet] isConnection]) {
        [self getData];
    }else{
        [self.database getFramentDataFromDataBaseSuccess:^(NSArray *arr) {
            self.framentList = (NSMutableArray*)arr;
            [self.tableView reloadData];
        } fail:^(NSError *err) {
            NSLog(@"%@",err);
        }];
    }
}
- (void)getData{
    [[YPNetWorking shareNetWorking] getDictWithURL:[YPMakeURL shareMakeURL].homePageFragmentHeaderURL dict:[YPMakeURL shareMakeURL].homePageParameterFragmentDic success:^(NSDictionary *dict) {
        [self.database deleteFramentSuccess:^{
        } fail:^(NSError *err) {
        }];
        [self.database insertDataWithFramentDic:dict success:^{
        } fail:^(NSError *err) {
            NSLog(@"插入失败");
        }];
        self.framentList = @[].mutableCopy;
        for (NSDictionary *tempDic in dict[@"data"][@"list"]) {
            YPFramentModel *model = [[YPFramentModel alloc]init];
            [model setValuesForKeysWithDictionary:tempDic];
            NSString *login = [[NSUserDefaults standardUserDefaults] objectForKey:@"login"];
            if (login == nil || [login isEqualToString:@"nlogin"]) {
                //nothing
            }else{
                NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
                [self.like isLikeWith:model.contentid name:name success:^(BOOL flag) {
                    if (flag) {
                        model.like++;
                    }
                    model.flag = flag;
                }];
            }
            [self.framentList addObject:model];
        }
        [self.tableView reloadData];
    } fail:^(NSError *err) {
    }];
}
- (void)upFreash{
    if ([[YPJudgeNet shareJudgeNet] isConnection]) {
        [[YPNetWorking shareNetWorking] getDictWithURL:[YPMakeURL shareMakeURL].homePageFragmentHeaderURL dict:[YPMakeURL shareMakeURL].homePageParameterFragmentDic success:^(NSDictionary *dict) {
            [self.framentList removeAllObjects];
            self.framentList = @[].mutableCopy;
            for (NSDictionary *tempDic in dict[@"data"][@"list"]) {
                YPFramentModel *model = [[YPFramentModel alloc]init];
                [model setValuesForKeysWithDictionary:tempDic];
                NSString *login = [[NSUserDefaults standardUserDefaults] objectForKey:@"login"];
                if (login == nil || [login isEqualToString:@"nlogin"]) {
                    //nothing
                }else{
                    NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
                    [self.like isLikeWith:model.contentid name:name success:^(BOOL flag) {
                        if (flag) {
                            model.like++;
                        }
                        model.flag = flag;
                    }];
                }
                [self.framentList addObject:model];
            }
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
        } fail:^(NSError *err) {
        }];
    }else{
        [self alertController:@"请检查网络"];
        [self.tableView.mj_header endRefreshing];
    }
}
static NSInteger num;
- (void)downFresh{
    if ([[YPJudgeNet shareJudgeNet] isConnection]) {
        num++;
        flag += 14 + num;
        [[YPNetWorking shareNetWorking] getDictWithURL:[YPMakeURL shareMakeURL].homePageFragmentHeaderURL dict:[[YPMakeURL shareMakeURL]makePageParameterFragmentDicWithNum:flag] success:^(NSDictionary *dict) {
            for (NSDictionary *tempDic in dict[@"data"][@"list"]) {
                YPFramentModel *model = [[YPFramentModel alloc]init];
                [model setValuesForKeysWithDictionary:tempDic];
                NSString *login = [[NSUserDefaults standardUserDefaults] objectForKey:@"login"];
                if (login == nil || [login isEqualToString:@"nlogin"]) {
                    //nothing
                }else{
                    NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
                    [self.like isLikeWith:model.contentid name:name success:^(BOOL flag) {
                        if (flag) {
                            model.like++;
                        }
                        model.flag = flag;
                    }];
                }
                [self.framentList addObject:model];
            }
            [self.tableView reloadData];
            [self.tableView.mj_footer endRefreshing];
        } fail:^(NSError *err) {
        }];
    }else{
        [self alertController:@"请检查网络"];
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.framentList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YPFragmentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YPFragmentCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    YPFramentModel *model = self.framentList[indexPath.row];
    cell.userImage.layer.masksToBounds = YES;
    cell.userImage.layer.cornerRadius = 20;
    cell.timeLable.text = model.addtime_f;
    [cell.userImage sd_setImageWithURL:[NSURL URLWithString:model.icon] placeholderImage:[UIImage imageNamed:@"16"]];
    cell.userName.text = model.uname;
    [cell.likeButton addTarget:self action:@selector(likeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell.likeButton setBackgroundImage:[UIImage imageNamed:@"iconfont-xihuan-2"] forState:(UIControlStateNormal)];
    cell.likeButton.tag = 900 + indexPath.row;
    cell.likeLable.text = [NSString stringWithFormat:@"%ld",(long)model.like];
    cell.contentLable.numberOfLines = 0;
    cell.contentLable.font = [UIFont systemFontOfSize:15];
    if ([model.coverimg isEqualToString:@""]) {
        if (cell.framentImage.hight > 0) {
            cell.framentImage.hight = 0;
        }
        self.imageHight = 0;
        if ([model.content isEqualToString:@""]){
            cell.contentLable.text = @"有人在唱歌";
        }else{
            float contentH = [self stringHight:model.content width:cell.width - 40];
            cell.contentLable.y = CGRectGetMaxY(cell.userImage.frame) + 10;
            cell.contentLable.text = model.content;
            cell.contentLable.hight = contentH;
            self.worldH = contentH;
        }
    }else{
        NSArray *arr = [model.coverimg_wh componentsSeparatedByString:@"*"];
        float imgH = [arr[0] floatValue];
        float imgW = [arr[1] floatValue];
        float cellImgH = (imgW / imgH) * (cell.width - 40);
        cell.framentImage.y = CGRectGetMaxY(cell.userImage.frame) + 10;
        cell.framentImage.hight = cellImgH;
        [cell.framentImage sd_setImageWithURL:[NSURL URLWithString:model.coverimg] placeholderImage:[UIImage imageNamed:@"16"]];
        self.imageHight = cellImgH;
        if ([model.content isEqualToString:@""]) {
            self.imageHight = cellImgH;
        }else{
            float contentH = [self stringHight:model.content width:cell.width - 40];
            cell.contentLable.y = CGRectGetMaxY(cell.userImage.frame) + self.imageHight + 20;
            cell.contentLable.hight = contentH;
            self.worldH = contentH;
            cell.contentLable.text = model.content;
        }
    }
    [cell.likeButton setBackgroundImage:[UIImage imageNamed:@"iconfont-xihuan-2"] forState:(UIControlStateNormal)];
    if (model.flag) {
        [cell.likeButton setBackgroundImage:[UIImage imageNamed:@"iconfont-xihuan"] forState:(UIControlStateNormal)];
    }
    return cell;
}
- (void)likeButtonAction:(UIButton*)sender{
    NSIndexPath *index = [NSIndexPath indexPathForRow:sender.tag-900 inSection:0];
    YPFragmentCell *cell = [self.tableView cellForRowAtIndexPath:index];
    YPFramentModel *model = self.framentList[sender.tag - 900];
    NSString *login = [[NSUserDefaults standardUserDefaults] objectForKey:@"login"];
    NSString *name  = nil;
    if (login == nil || [login isEqualToString:@"nlogin"]) {
        [self alertController:@"请先登录"];
        return;
    }else{
        name = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
    }
    model.flag = !model.flag;
    if (model.flag) {
        [cell.likeButton setBackgroundImage:[UIImage imageNamed:@"iconfont-xihuan"] forState:(UIControlStateNormal)];
        cell.likeLable.text = [NSString stringWithFormat:@"%d",++model.like];
        [self alertController:@"谢谢喜欢"];
        [self.like addLikeWithUrl:model.contentid name:name];
    }else{
        [cell.likeButton setBackgroundImage:[UIImage imageNamed:@"iconfont-xihuan-2"] forState:(UIControlStateNormal)];
        cell.likeLable.text = [NSString stringWithFormat:@"%d",--model.like];
        [self alertController:@"取消喜欢"];
        [self.like deleteLike:model.contentid name:name];
    }
}
-(CGFloat)stringHight:(NSString*)str width:(CGFloat)width{
    CGRect temp = [str boundingRectWithSize:CGSizeMake(width, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil];
    return temp.size.height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return self.imageHight + self.worldH + 110;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    YPFramentModel *model = self.framentList[indexPath.row];
    NSString *url = [NSString stringWithFormat:@"http://pianke.me/webview/%@",model.contentid];
    YPWebViewVC *webVC = [[YPWebViewVC alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:webVC];
    webVC.tingID = url;
    webVC.type = @"碎片";
    YPUser *fUser = [[YPUser alloc]init];
    [fUser setValuesForKeysWithDictionary:model.userinfo];
    webVC.user = fUser;
    webVC.like = model.like;
    webVC.shareImage = model.coverimg;
    webVC.shareTitle = @"无题";
    [self.navigationController presentViewController:nav animated:YES completion:nil];
}

- (void)alertController:(NSString*)str{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:str preferredStyle:UIAlertControllerStyleAlert];        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}

+(instancetype)shareFramentVC{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        fragmentVC = [[YPHomePageFragmentVC alloc]init];
    });
    return fragmentVC;
}
- (YPLikeHelper *)like{
    if (_like == nil) {
        _like = [[YPLikeHelper alloc]init];
    }
    return _like;
}

- (YPDataBase *)database{
    if (_database == nil) {
        _database = [[YPDataBase alloc]init];
    }
    return _database;
}
@end
